var Buffer = require('buffer/').Buffer;
/*
    demo
    console.log(Utils.custom_encode("abe4eabcfde", "123qwe!@#"));
    console.log(Utils.custom_decode("abe4eabcfde", "MTQ2fDE0OHwxNTJ8MTY1fDIyMHwxOTl8MTMyfDE2NnwxMzU="));
 */
export default Utils = {
    // 加密
    custom_encode: function (token, password) {
        if(token == null || password==null){
            return "";
        }

        var password = new Buffer(password).toString('base64');

        var arr = password.split("");
        var token_arr = token.split("");
        var new_arr = []

        var length = (token_arr.length / arr.length);
        for (var i = 0; i < arr.length; i++) {
            var char_code = arr[i].toString();
            char_code = char_code.charCodeAt(0);
            var token_index = parseInt(length * i);
            var token_char = (token_arr[token_index]).toString();
            var new_char_code = char_code + token_char.charCodeAt();

            new_arr.push(new_char_code);
        }

        var result = new Buffer(new_arr.join("|")).toString('base64');
        return result;
    },

    // 解密
    custom_decode: function (token, base64Str){
        var b = new Buffer(base64Str , 'base64')
        var str = b.toString();
        var arr = str.split("|");
        var token_arr = token.split("");
        var new_arr = []

        var length = (token_arr.length / arr.length);
        for(var i=0; i < arr.length; i ++){
            var char_code = parseInt(arr[i]);
            var token_index = parseInt(length * i);
            var token_char = (token_arr[token_index]).toString();
            var new_char_code = char_code - token_char.charCodeAt();

            new_arr.push(String.fromCharCode(new_char_code));
        }

        return new_arr.join("")
    }
}